package com.cn.shuangzi.ad.manager;

import android.app.Activity;

import com.bytedance.msdk.api.AdError;
import com.bytedance.msdk.api.GMAdEcpmInfo;
import com.bytedance.msdk.api.reward.RewardItem;
import com.bytedance.msdk.api.v2.GMAdConstant;
import com.bytedance.msdk.api.v2.GMMediationAdSdk;
import com.bytedance.msdk.api.v2.GMSettingConfigCallback;
import com.bytedance.msdk.api.v2.ad.interstitialFull.GMInterstitialFullAd;
import com.bytedance.msdk.api.v2.ad.interstitialFull.GMInterstitialFullAdListener;
import com.bytedance.msdk.api.v2.ad.interstitialFull.GMInterstitialFullAdLoadCallback;
import com.bytedance.msdk.api.v2.slot.GMAdOptionUtil;
import com.bytedance.msdk.api.v2.slot.GMAdSlotInterstitialFull;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.YlhErrorInfo;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.OnAdClosedListener;
import com.cn.shuangzi.ad.view.AlertVipDialog;
import com.cn.shuangzi.util.SZUtil;
import com.qq.e.ads.interstitial2.UnifiedInterstitialAD;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;

public class AdInterstitialFullManager {

    private GMInterstitialFullAd mGMInterstitialFullAd;
    private Activity mActivity;
    private Class<?> classBuyVip;
    private OnAdClosedListener onAdClosedListener;
    private GMInterstitialFullAdLoadCallback mGMInterstitialFullAdLoadCallback = new GMInterstitialFullAdLoadCallback() {
        @Override
        public void onInterstitialFullLoadFail(@NonNull AdError adError) {
            SZUtil.logError("展示获取失败："+adError);
        }

        @Override
        public void onInterstitialFullAdLoad() {
            SZUtil.logError("插屏获取成功");
            showAd(classBuyVip);
            printSHowAdInfo();
        }

        @Override
        public void onInterstitialFullCached() {

        }
    };
    private String mAdUnitId; //广告位
    private String scenarioId; //广告位

    public AdInterstitialFullManager(Activity activity,Class<?> classBuyVip) {
        this(activity,classBuyVip,null);
    }
    public AdInterstitialFullManager(Activity activity,Class<?> classBuyVip, OnAdClosedListener onAdClosedListener) {
        mActivity = activity;
        this.classBuyVip = classBuyVip;
        this.onAdClosedListener = onAdClosedListener;
    }

    public GMInterstitialFullAd getGMInterstitialFullAd() {
        return mGMInterstitialFullAd;
    }


    public void loadAdWithCallback(final String adUnitId,String scenarioId) {
        this.mAdUnitId = adUnitId;
        this.scenarioId = scenarioId;
        /**
         * 判断当前是否存在config 配置 ，如果存在直接加载广告 ，如果不存在则注册config加载回调
         */
        if (GMMediationAdSdk.configLoadSuccess()) {
            SZUtil.logError("load ad 当前config配置存在，直接加载广告");
            loadAd();
        } else {
            SZUtil.logError("load ad 当前config配置不存在，正在请求config配置....");
            ADManager.getInstance().initGMAd();
            GMMediationAdSdk.registerConfigCallback(mSettingConfigCallback); //不用使用内部类，否则在ondestory中无法移除该回调
        }
    }

    private void loadAd() {
        /**
         * 注：每次加载插全屏广告的时候需要新建一个GMInterstitialFullAd，否则可能会出现广告填充问题
         * （ 例如：mInterstitialFullAd = new GMInterstitialFullAd(this, adUnitId);）
         */
        //Context 必须传activity
        mGMInterstitialFullAd = new GMInterstitialFullAd(mActivity, mAdUnitId);

//        Map<String, String> customData = new HashMap<>();
//        customData.put(GMAdConstant.CUSTOM_DATA_KEY_GDT, "gdt custom data");//目前仅支持gdt
        // 其他需要透传给adn的数据。

        GMAdSlotInterstitialFull adSlotInterstitialFull = new GMAdSlotInterstitialFull.Builder()
                .setGMAdSlotBaiduOption(GMAdOptionUtil.getGMAdSlotBaiduOption().build())
                .setGMAdSlotGDTOption(GMAdOptionUtil.getGMAdSlotGDTOption().build())
                .setDownloadType(GMAdConstant.DOWNLOAD_TYPE_POPUP)
                .setImageAdSize(600, 600)  //设置宽高 （插全屏类型下_插屏广告使用）
                .setMuted(true)
                .setVolume(0f)
                .setScenarioId(scenarioId)
                .setUserID("user123")//用户id,必传参数 (插全屏类型下_全屏广告使用)
//                .setCustomData(customData)
//                .setRewardName("金币") //奖励的名称
//                .setRewardAmount(3)  //奖励的数量
                .setOrientation(GMAdConstant.VERTICAL)//必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL; (插全屏类型下_全屏广告使用)
                .build();

        //请求广告，调用插屏广告异步请求接口
        mGMInterstitialFullAd.loadAd(adSlotInterstitialFull, mGMInterstitialFullAdLoadCallback);
    }

    public void showAd(final Class<?> classVip){
        if(mGMInterstitialFullAd == null){
            return;
        }
        mGMInterstitialFullAd.setAdInterstitialFullListener(new GMInterstitialFullAdListener() {

            @Override
            public void onInterstitialFullShow() {
                GMAdEcpmInfo gmAdEcpmInfo = mGMInterstitialFullAd.getShowEcpm();
                SZUtil.logError("插屏显示成功！Ecpm="+gmAdEcpmInfo);
                if(gmAdEcpmInfo!=null) {
                    ADManager.getInstance().setGroMoreInteractionAdTodayShown();
                    if(!ADManager.getInstance().isYlhPlatform(gmAdEcpmInfo.getAdNetworkPlatformName())) {
                        UnifiedInterstitialAD unifiedInterstitialAD = ADManager.getInstance().getCurrentUnifiedInterstitialAD();
                        YlhErrorInfo ylhErrorInfo = ADManager.getInstance().getInterstitialErrorInfo();
                        if (gmAdEcpmInfo != null && unifiedInterstitialAD != null && ylhErrorInfo != null) {
                            int ecpm = ylhErrorInfo.getPrice();
                            try {
                                if (ecpm <= 0) {
                                    ecpm = 40 * ADConst.YUAN;
                                }
                                double preEcpm = Double.parseDouble(gmAdEcpmInfo.getPreEcpm());
                                if(preEcpm>0) {
                                    ecpm = (int) (preEcpm + 1* ADConst.YUAN);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            ylhErrorInfo.setPrice(ecpm);
                            unifiedInterstitialAD.sendLossNotification(ecpm, ylhErrorInfo.getReason(), ylhErrorInfo.getAdnId());
                            SZUtil.logError("上报优量汇插屏竞价失败：ylhErrorInfo" + ylhErrorInfo);
                        }
                    }
                }

                ADManager.getInstance().setCurrentUnifiedInterstitialAD(null);
                ADManager.getInstance().setInterstitialErrorInfo(null);
            }

            @Override
            public void onInterstitialFullShowFail(@NonNull AdError adError) {
                SZUtil.logError("展示显示失败："+adError);
                ADManager.getInstance().setCurrentUnifiedInterstitialAD(null);
                ADManager.getInstance().setInterstitialErrorInfo(null);
            }

            @Override
            public void onInterstitialFullClick() {

            }

            @Override
            public void onInterstitialFullClosed() {
                if(classVip!=null&&!mActivity.isFinishing()) {
                    new AlertVipDialog(mActivity, classVip).show();
                }
                if(onAdClosedListener!=null){
                    onAdClosedListener.onAdClosed();
                }
            }

            @Override
            public void onVideoComplete() {

            }

            @Override
            public void onVideoError() {

            }

            @Override
            public void onSkippedVideo() {

            }

            @Override
            public void onAdOpened() {

            }

            @Override
            public void onAdLeftApplication() {

            }

            @Override
            public void onRewardVerify(@NonNull RewardItem rewardItem) {

            }
        });
        mGMInterstitialFullAd.showAd(mActivity);
    }
    public void destroy() {
        if (mGMInterstitialFullAd != null) {
            mGMInterstitialFullAd.destroy();
        }
        mActivity = null;
        mGMInterstitialFullAdLoadCallback = null;
        GMMediationAdSdk.unregisterConfigCallback(mSettingConfigCallback); //注销config回调
    }

    /**
     * config回调
     */
    private GMSettingConfigCallback mSettingConfigCallback = new GMSettingConfigCallback() {
        @Override
        public void configLoad() {
            SZUtil.logError("load ad 在config 回调中加载广告");
            loadAd();
        }
    };


    //-----------以下方法非必须 ，按需使用--------------

    //展示已经加载广告的信息
    public void printLoadAdInfo() {
        if (mGMInterstitialFullAd == null) {
            return;
        }
        /**
         * 获取已经加载的clientBidding ，多阶底价广告的相关信息
         */
        List<GMAdEcpmInfo> gmAdEcpmInfos = mGMInterstitialFullAd.getMultiBiddingEcpm();
        if (gmAdEcpmInfos != null) {
            for (GMAdEcpmInfo info : gmAdEcpmInfos) {
                SZUtil.logError("***多阶+client相关信息*** AdNetworkPlatformId" + info.getAdNetworkPlatformId()
                        + "  AdNetworkRitId:" + info.getAdNetworkRitId()
                        + "  ReqBiddingType:" + info.getReqBiddingType()
                        + "  PreEcpm:" + info.getPreEcpm()
                        + "  LevelTag:" + info.getLevelTag()
                        + "  ErrorMsg:" + info.getErrorMsg()
                        + "  request_id:" + info.getRequestId());
            }
        }

        /**
         * 获取实时填充/缓存池中价格最优的代码位信息即相关价格信息，每次只有一个信息
         */
        GMAdEcpmInfo gmAdEcpmInfo = mGMInterstitialFullAd.getBestEcpm();
        if (gmAdEcpmInfo != null) {
            SZUtil.logError("***实时填充/缓存池中价格最优的代码位信息*** AdNetworkPlatformId" + gmAdEcpmInfo.getAdNetworkPlatformId()
                    + "  AdNetworkRitId:" + gmAdEcpmInfo.getAdNetworkRitId()
                    + "  ReqBiddingType:" + gmAdEcpmInfo.getReqBiddingType()
                    + "  PreEcpm:" + gmAdEcpmInfo.getPreEcpm()
                    + "  LevelTag:" + gmAdEcpmInfo.getLevelTag()
                    + "  ErrorMsg:" + gmAdEcpmInfo.getErrorMsg()
                    + "  request_id:" + gmAdEcpmInfo.getRequestId());
        }

        /**
         * 获取获取当前缓存池的全部信息
         */
        List<GMAdEcpmInfo> gmCacheInfos = mGMInterstitialFullAd.getCacheList();
        if (gmCacheInfos != null) {
            for (GMAdEcpmInfo info : gmCacheInfos) {
                SZUtil.logError("***缓存池的全部信息*** AdNetworkPlatformId" + info.getAdNetworkPlatformId()
                        + "  AdNetworkRitId:" + info.getAdNetworkRitId()
                        + "  ReqBiddingType:" + info.getReqBiddingType()
                        + "  PreEcpm:" + info.getPreEcpm()
                        + "  LevelTag:" + info.getLevelTag()
                        + "  ErrorMsg:" + info.getErrorMsg()
                        + "  request_id:" + info.getRequestId());
            }
        }
    }

    //打印加载失败的adn错误信息
    public void printLoadFailAdnInfo() {
        if (mGMInterstitialFullAd == null) {
            return;
        }
        // 获取本次waterfall加载中，加载失败的adn错误信息。
        SZUtil.logError("InterstitialFull ad loadinfos: " + mGMInterstitialFullAd.getAdLoadInfoList());

    }

    //打印已经展示的广告信息
    public void printSHowAdInfo() {
        if (mGMInterstitialFullAd == null) {
            return;
        }
        GMAdEcpmInfo gmAdEcpmInfo = mGMInterstitialFullAd.getShowEcpm();
        SZUtil.logError("当前插屏:"+gmAdEcpmInfo);
        if (gmAdEcpmInfo == null) {
            return;
        }
        String msg = "展示的广告信息 ： adNetworkPlatformName: " + gmAdEcpmInfo.getAdNetworkPlatformName() + "   adNetworkRitId：" + gmAdEcpmInfo.getAdNetworkRitId() + "   preEcpm: " + gmAdEcpmInfo.getPreEcpm();
        SZUtil.logError(msg);
    }

}
